package Utilities;

/**BufferedReader.java
 * 
 * This class is a utility to help read data from the map file
 * to store it into the MapSquare and the Map classes.
 * 
 * @author Christopher Carithers
 * Last Updated: 4/15/2014
 *
 */

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;

public class BufferedReader 
{
	private String m_FileName;
	private final Path m_FileNamePath;
	private char m_CharacterArrayMap[][];
	private int m_NumberOfX;
	private int m_NumberOfY;
	
	public BufferedReader(String fileName, int numberOfX, int numberOfY)
	{
		m_FileName = fileName;
		m_FileNamePath = Paths.get(fileName);
		m_NumberOfX = numberOfX;
		m_NumberOfY = numberOfY;
		m_CharacterArrayMap = new char[m_NumberOfX][m_NumberOfY];
	}
	
	public static char[] processLineInFile(String aLine)
	{
		Scanner scanner = new Scanner(aLine);
		scanner.useDelimiter(" ");
		
		String singleCharacterAsString = "";
		char[] singleCharacterArray = new char[16];
		char singleCharacter;
		
		int index = 0;
		while(scanner.hasNext())
		{
		   singleCharacterAsString = scanner.next();
		   singleCharacter = singleCharacterAsString.charAt(0);
		   if(singleCharacter == '0')
		   {
			   singleCharacter = ' ';
		   }
		   singleCharacterArray[index] = singleCharacter;
		   index++;
		}
		
		return singleCharacterArray;
	}
	
	private final static Charset ENCODING = StandardCharsets.UTF_8;
	private static void log(Object aObject)
	{
		System.out.println(String.valueOf(aObject));
	}
	
    public final char[] printCharacterMapArray() throws IOException
    {
    	char[] characterMapArray = null;
    	try(Scanner scanner = new Scanner(m_FileNamePath, ENCODING.name()))
    	{
    		while(scanner.hasNextLine())
    		{
    			characterMapArray = processLineInFile(scanner.nextLine());
    			return characterMapArray;
    		}
    	}
		return characterMapArray;
    }
    
    public void setCharacterMapArray() throws IOException
    {
	   char[] characterMapArray = null;
	   try(Scanner scanner = new Scanner(m_FileNamePath, ENCODING.name()))
	   {
		  int i = 0;
		  int j = 0;
		  while(scanner.hasNextLine())
		  {
			 characterMapArray = processLineInFile(scanner.nextLine());
			 for(j = 0; j < 16; j++)
			    m_CharacterArrayMap[i][j] = characterMapArray[j];
			 i++;
		  }
	   }
    }
    
    public char[][] getCharacterMapArray()
    {
       return m_CharacterArrayMap;
    }
}
